package com.lingjtx.im.core.common;

import com.lingjtx.common.core.RedisOptions;
import com.lingjtx.common.core.constant.RedisConfig;
import com.lingjtx.common.core.token.UserDetail;
import io.netty.channel.Channel;

public class SessionManager {

    // IM 用户在线存储：redis value 为服务节点id（node@host:port）
    // rabbitmq 根据用户连接的服务节点id（node@host:port）来获取websocket Channel
    public static void registerSession(UserDetail userDetail, Channel channel, String nodeId, RedisOptions redis) {
        ChannelPool.bind(userDetail, channel);
        // Redis 存储在线状态（集群下）
        redis.set(RedisConfig.IM_USER_ONLINE + userDetail.getUserId(), nodeId, RedisConfig.TIMEOUT_REFRESH_TOKEN);
    }

    public static void removeSession(Channel channel, RedisOptions redis) {
        Long userId = ChannelPool.getUserId(channel);
        if (ChannelPool.getChannels(userId).isEmpty()) {
            redis.delete(RedisConfig.IM_USER_ONLINE + userId);
        }
        ChannelPool.unbind(channel);
    }

    public static boolean isUserOnline(Long userId, RedisOptions redis) {
        return redis.exists(RedisConfig.IM_USER_ONLINE + userId);
    }
}
